package com.nitor.dns.validate;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

import org.xbill.DNS.DClass;
import org.xbill.DNS.ExtendedResolver;
import org.xbill.DNS.Message;
import org.xbill.DNS.Name;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.Section;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;

public class DNS_Validator {
	
	private final int type = Type.CERT;
	private final int dclass = DClass.IN;
	
	private Name domain;
	private Resolver res;
	
	public DNS_Validator(Name domain) throws UnknownHostException{
		this.domain = domain;
		res = new ExtendedResolver();
	}
	
	public String resolve(){
		
		Record[] answers;
		String certInfo = null;
		StringBuffer result = new StringBuffer();
		
		Record rec = Record.newRecord(this.domain, this.type, this.dclass);
		
		try {
			answers = getAnswers(rec);
			
			if(answers.length == 0){
				result.append("Fail: No results returned\n\n");
			}else{
			
				certInfo = answers[0].rdataToString();
			
				if(!validate(certInfo.toString()))
					result.append("Fail: Incorrect Certificate Type\n\n");
				else{					
					result.append("Pass: Correct Certificate\n\n");
					CertDecrypt ce = new CertDecrypt();
					result.append(ce.recordToCert(certInfo));
				}
			}
		}catch (IOException e) {
			result.append("Fail: " + e);
		}
				
		return result.toString();
	}
	
	private Record[] getAnswers(Record rec) throws IOException{
		Message query = Message.newQuery(rec);
		Message response = res.send(query);
		
		return response.getSectionArray(Section.ANSWER);
	}
	
	private Boolean validate(String answer){
		StringTokenizer st = new StringTokenizer(answer);
		int certType = Integer.parseInt(st.nextToken());
		if(certType==1 || certType==4){
			return true;
		}else return false;
	}
	
	
	public static void main(String args[]){
		try {
			DNS_Validator valid_dns = new DNS_Validator(new DNS_Parser().getAddress("postmaster@3bignotes.com"));
			System.out.println(valid_dns.resolve());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TextParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
